//
//  AppDelegate.m
//  FinderBox
//
//  Created by JiYi on 2018/10/11.
//  Copyright © 2018 JiYi. All rights reserved.
//

#import "AppDelegate.h"
#import "JYBaseWebViewController.h"
#import "JYFullScreenAdView.h"



@interface AppDelegate ()<UNUserNotificationCenterDelegate, JPUSHRegisterDelegate>

@property (nonatomic, strong) NSDictionary * launchOptions;


@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    [[UINavigationBar appearance] setTintColor:UIColor.blackColor];
    [[UINavigationBar appearance] setBarTintColor:UIColor.whiteColor];

    [[UITabBar appearance] setTranslucent:NO];
    
    self.launchOptions = launchOptions;
    
    [AVOSCloud setApplicationId:@"p3CEJUte2R3XpKAi31z6m5bv-gzGzoHsz" clientKey:@"yGMhqiEVtJhoFSnRmgosKrvy"];
    
    [AVOSCloud setAllLogsEnabled:NO];
    
    [UserNotificationManager registerLocalNotification];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadRootVC) name:@"ReloadRootVC" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(PPPushKey:) name:@"PPPushKey" object:nil];
    
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor = [UIColor whiteColor];
    self.window.rootViewController = [[JYTabBarController alloc] init];
    [self.window makeKeyAndVisible];
    

    [UNUserNotificationCenter currentNotificationCenter].delegate = self;
    [self addAdView];
    [self getADImageURL];

    return YES;
}

#pragma mark - 添加启动封面图
- (void)addAdView {
    JYFullScreenAdView * adView = [[JYFullScreenAdView alloc] init];
    adView.tag = 1000;
    adView.duration = 3;
    adView.waitTime = 3;
    adView.skipType = SkipButtonTypeNormalTimeAndText;
    adView.adImageTapBlock = ^(NSString *content) {
        if (content.length != 0) {
            JYSubWebViewController * sub = [[JYSubWebViewController alloc] init];
            sub.urlStr = content;
            sub.hidesBottomBarWhenPushed = YES;
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [[AppDelegate presentingVC].navigationController pushViewController:sub animated:YES];
            });
        }
    };
    [self.window addSubview:adView];
}
/** 获取封面图URL */
- (void)getADImageURL
{
    JYFullScreenAdView *adView = (JYFullScreenAdView *)[self.window viewWithTag:1000];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        AVObject * lanuchObj = [AVObject objectWithClassName:@"LaunchAdView" objectId:@"5bc413d7808ca400721bdae4"];
        [lanuchObj fetchInBackgroundWithBlock:^(AVObject * _Nullable object, NSError * _Nullable error) {
            if (!error) {
                NSString * imageUrl = object[@"data"][@"imageUrl"];
                NSString * jumpUrl = object[@"data"][@"jumpUrl"];
                
                [adView reloadAdImageWithUrl:imageUrl content:jumpUrl];
            }
        }];
    });
}

- (void)playBeep
{
    
    SystemSoundID sound = kSystemSoundID_Vibrate;
    
    //使用系统铃声
    NSString *path = [NSString stringWithFormat:@"/System/Library/Audio/UISounds/%@.%@",@"new-mail",@"caf"];
    //使用自定义铃声
    //    NSString *path = [[NSBundle mainBundle] pathForResource:@"QRCodeRead"ofType:@"wav"];　　//需将音频资源copy到项目<br>
    if (path) {
        OSStatus error = AudioServicesCreateSystemSoundID((__bridge CFURLRef)[NSURL fileURLWithPath:path],&sound);
        if (error != kAudioServicesNoError) {
            sound = 0;
        }
    }
    
    AudioServicesPlaySystemSound(sound);//播放声音
    AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);//静音模式下震动
}

#pragma mark --- UNUserNotificationCenterDelegate
- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"didReciveNotification" object:nil userInfo:@{@"idf" : notification.request.identifier}];
    completionHandler(UNNotificationPresentationOptionAlert + UNNotificationPresentationOptionSound + UNNotificationPresentationOptionBadge);
    [self playBeep];
}
- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(nonnull UNNotificationResponse *)response withCompletionHandler:(nonnull void (^)(void))completionHandler{
    [self handCommnet:response];
    [self playBeep];
    completionHandler();
}
-(void)handCommnet:(UNNotificationResponse *)response
{
    NSString *actionIdef = response.actionIdentifier;
    NSDate *date;
    if ([actionIdef isEqualToString:ActionStop]) {
        return;
    }else if ([actionIdef isEqualToString:ActionFiveMin]) {
        date = [NSDate dateWithTimeIntervalSinceNow:5 * 60];
    }else if ([actionIdef isEqualToString:ActionHalfAnHour]) {
        date = [NSDate dateWithTimeIntervalSinceNow:30 * 60];
    }else if ([actionIdef isEqualToString:ActionOneHour]) {
        date = [NSDate dateWithTimeIntervalSinceNow:60 * 60];
    }
    
    if (date) {
        [UserNotificationManager addNotificationWithContent:response.notification.request.content identifer:response.notification.request.identifier isRepeat:NO dateComponents:[UserNotificationManager componentsWithDate:date] completionHandler:^(NSError *error) {
            NSLog(@"%@",error);
        }];
        
    }else {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"didReciveNotification" object:nil userInfo:@{@"idf" : response.notification.request.identifier}];
    }
}
#pragma mark - 重加载
- (void)reloadRootVC {
    self.window.rootViewController = [[JYTabBarController alloc] init];
}
- (void)PPPushKey:(NSNotification *)noti {
    NSString * ppKey = noti.object;
    
    JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
    entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound;
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        
    }
    [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
    
    [JPUSHService setupWithOption:self.launchOptions appKey:ppKey
                          channel:@"App Store"
                 apsForProduction:YES
            advertisingIdentifier:nil];
}

- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    
    /// Required - 注册 DeviceToken
    [JPUSHService registerDeviceToken:deviceToken];
}

#pragma mark- JPUSHRegisterDelegate

// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
    // Required
    NSDictionary * userInfo = notification.request.content.userInfo;
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
    }
    completionHandler(UNNotificationPresentationOptionAlert); // 需要执行这个方法，选择是否提醒用户，有 Badge、Sound、Alert 三种类型可以选择设置
}

// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
    // Required
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
    }
    //  通过消息打开
    if ([[userInfo allKeys] containsObject:@"data"]) {
        NSDictionary * dataDict = userInfo[@"data"];
        if ([[dataDict allKeys] containsObject:@"url"]) {
            //  取type
            NSString * type = [NSString stringWithFormat:@"%@",dataDict[@"url"]];
            JYSubWebViewController * sub = [[JYSubWebViewController alloc] init];
            sub.urlStr = type;
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [[AppDelegate presentingVC].navigationController pushViewController:sub animated:YES];
            });
        }
    }
    
    completionHandler();  // 系统要求执行这个方法
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    
    // Required, iOS 7 Support
    [JPUSHService handleRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    
    // Required, For systems with less than or equal to iOS 6
    [JPUSHService handleRemoteNotification:userInfo];
}


- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    
    if ([UIApplication sharedApplication].applicationIconBadgeNumber>0){
        UILocalNotification *localNote = [[UILocalNotification alloc] init];
        localNote.applicationIconBadgeNumber = -1;
        [[UIApplication sharedApplication] scheduleLocalNotification:localNote];
        [[UIApplication sharedApplication] cancelLocalNotification:localNote];
    }
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

//获取到当前所在的视图
+ (UIViewController *)presentingVC{
    UIWindow * window = [[UIApplication sharedApplication] keyWindow];
    if (window.windowLevel != UIWindowLevelNormal){
        NSArray *windows = [[UIApplication sharedApplication] windows];
        for(UIWindow * tmpWin in windows){
            if (tmpWin.windowLevel == UIWindowLevelNormal){
                window = tmpWin;
                break;
            }
        }
    }
    UIViewController *result = window.rootViewController;
    while (result.presentedViewController) {
        result = result.presentedViewController;
    }
    if ([result isKindOfClass:[UITabBarController class]]) {
        result = [(UITabBarController *)result selectedViewController];
    }
    if ([result isKindOfClass:[UINavigationController class]]) {
        result = [(UINavigationController *)result topViewController];
    }
    return result;
}



@end
